﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Threading;
using System.Windows.Threading;
using System.Diagnostics;
using System.Xml;
using Indigo.Quibbler.Properties;

namespace Indigo.Quibbler
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.DispatcherUnhandledException +=new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            this.Exit += new ExitEventHandler(App_Exit);
            
            
            SplashScreen screen = new SplashScreen("Images/splash_screen.jpg");
            screen.Show(false);
            Thread.Sleep(1000);
            screen.Close(new TimeSpan(1000));
        }

        #region Event Handlers
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                Utilities.Log("Unhandled Exception: ", e.Exception);
                string message = "An unexpected exception has occurred. Application will now close." +
                    "\r\nThe details have been logged to " + Utilities.LogTarget;
                MessageBox.Show(message, "Unknow error", MessageBoxButton.OK, MessageBoxImage.Error);

                Application.Current.Shutdown();

                // Prevent default unhandled exception processing
                e.Handled = true;
            }
            catch { /* If error occurs in logging, supress it and let system handle the original error. */ }
        }

        private void App_Exit(object sender, ExitEventArgs e)
        {
            try
            {
                Library.LibManager libManager = new Indigo.Quibbler.Library.LibManager();
                libManager.CleanUp(Settings.Default.ContentDeleteFrequency);
            }
            catch (Exception ex)
            {
                Utilities.Log("Content Clean up Error: ", ex);
            }
        }
        #endregion
    }
}
